import React, { useEffect, useRef, useState } from 'react'
import { useLocation } from 'react-router-dom'
import './send.scss'
import { LeftOutline, AddCircleOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom/dist'
import { useSelector, useDispatch } from 'react-redux'
import { setfriends } from '../../store/userInfo/userinfo'
import socket from '../../socket'
import storage from '../../utils/storage'
import axios from '../../http/axios'
export default function Send() {
    const [file, setFile] = useState('');
    const [imagePreview, setImagePreview] = useState('');
    const [base64, setbase64] = useState('')
    const infile = useRef()
    const handleFileChange = (e) => {
        setseyle(true)
        const file = e.target.files[0];
        console.log(file);
        setFile(file);
        // 在这里进行文件处理，例如上传到服务器等
        const reader = new FileReader();
        reader.onload = (event) => {
            setImagePreview(event.target.result);
            setbase64(event.target.result);
        };
        reader.readAsDataURL(file);
    };
    const dis = useDispatch()
    const nav = useNavigate()
    const selfInfo = storage.get('selfInfo')
    const friends = useSelector(state => state.userinfo.friends)
    // console.log(selfInfo);
    const loc = useLocation()
    const toUser = JSON.parse(sessionStorage.getItem('toUser'))

    const [msg, setMsg] = useState('')
    const [msglist, setmsglist] = useState(storage.get(loc.state.user.othername) || [])
    const setTime = (value) => {
        let date = new Date(value)
        let y = date.getFullYear()
        let MM = date.getMonth() + 1
        MM = MM < 10 ? ('0' + MM) : MM
        let d = date.getDate()
        d = d < 10 ? ('0' + d) : d
        let h = date.getHours()
        h = h < 10 ? ('0' + h) : h
        let m = date.getMinutes()
        m = m < 10 ? ('0' + m) : m
        let s = date.getSeconds()
        s = s < 10 ? ('0' + s) : s
        return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
    }
    const [style, setseyle] = useState(false)
    useEffect(() => {
        socket.on('sendPrivateHistory', (data) => {

            setmsglist(data.chathistory)
            storage.set(data.othername, data.chathistory)
        })
        socket.emit('saveSocketId', selfInfo.account)

        document.getElementById('parent').scrollTop = document.getElementById('parent').scrollHeight

        socket.on('sendToOther', (data) => {
            setmsglist(data)
        })
    }, [])

    return (
        <div className='chatting_bgc'>
            <div className="head">
                <LeftOutline onClick={() => { nav(-1) }} className='left' />
                <span>{loc.state.user.othername}</span>
            </div>
            <div className="msg_box" id='parent'>
                {msglist.map((item, index) => {
                    console.log(item.content.includes('https://'));
                    if (item.self) {
                        return <div className='msg_right' key={index}>
                            {item.content.includes('https://') ? <img className='imgs' src={item.content} alt="" /> : <p>{item.content}</p>}
                            <img src={selfInfo.avatar} alt="" />
                        </div>

                    } else {
                        return <div className='msg_left' key={index}>

                            <img src={toUser.otheravatar} alt="" />
                            {item.content.includes('https://') ? <img className='imgs' src={item.content} alt="" /> : <p>{item.content}</p>}
                        </div>
                    }

                })}
            </div>

            <div className="bottom">
                <div className={style ? 'show' : 'noshow'}>

                    <input type="file" onChange={handleFileChange} style={{ display: 'none' }} ref={infile} />


                    <button id='x' onClick={() => { setseyle(false) }}>取消</button>

                    {file ? <img src={imagePreview} alt="Uploaded image" /> : ''}
                </div>
                <input className='input' type="text" value={msg} onChange={(e) => { setMsg(e.target.value) }} />
                <button onClick={async () => {
                    let form = new FormData()
                    form.append('file', file)
                    console.log(file);
                    let res = await axios.post('/upload2', form)
                    console.log(res.data);
                    var t = new Date().getTime()
                    let copy = [...msglist]
                    copy.push({
                        time: setTime(t),
                        self: true,
                        content: msg || res.data
                    })
                    setseyle(false)
                    setbase64('')
                    setFile('')
                    console.log(copy);
                    await setmsglist(copy)
                    //发射事件，保存聊天记录并通知对方
                    socket.volatile.emit('sendMsg', { selfaccount: selfInfo.account, otheraccount: toUser.otheraccount, chathistory: copy })
                    let copys = JSON.parse(JSON.stringify(friends))
                    let i = copys.findIndex(item => item.otheraccount === toUser.otheraccount)
                    copys[i].latestmsg.time = setTime(t)
                    copys[i].latestmsg.content = msg
                    copys[i].latestmsg.self = true
                    dis(setfriends(copys))
                    setMsg('')
                    const parent = document.getElementById('parent')
                    parent.scrollTop = parent.scrollHeight
                }}>发送</button>

                <AddCircleOutline className='addfile' onClick={() => {
                    infile.current.click()

                }} />
            </div>
        </div>
    )
}
